package com.ruoyi.doudian.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.AjaxUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.doudian.service.DoudianAuthService;
import com.ruoyi.doudian.vo.AccessTokenVO;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.DoudianUser;
import com.ruoyi.system.mapper.doudian.DoudianUserMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author X
 * @version 1.0
 * @ClassName DoudianAuthServiceImpl
 * @description
 * @date 2020/11/2
 **/
@Service
public class DoudianAuthServiceImpl implements DoudianAuthService {

    @Autowired
    private AjaxUtils ajaxUtils;
    // 令牌自定义标识
    @Value("${token.header}")
    private String header;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private DoudianUserMapper doudianUserMapper;

    /***
     * 抖店授权
     * @return
     */
    @Override
    public String doudianAuth() {
        String token = ServletUtils.getRequest().getHeader(this.header);
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
        }
        String url = "https://fxg.jinritemai.com/index.html#/ffa/open/applicationAuthorize?response_type=code&app_id=6863250841932285454&redirect_uri=http://zs.91gongju.cn/doudain/getAccessToken&state=" + token;
        return url;
    }

    /***
     * 获取accessToken
     * @param code
     * @return
     */
    @Override
    public AjaxResult getAccessToken(String code, String state) {
        Claims claims = tokenService.parseToken(state);
        // 解析对应的权限以及用户信息
        String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
        String userKey = tokenService.getTokenKey(uuid);
        // 获取到用户信息
        LoginUser loginUser = redisCache.getCacheObject(userKey);
        String url = "https://openapi-fxg.jinritemai.com/oauth2/access_token";
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("app_id", "6863250841932285454");
        hashMap.put("app_secret", "f56599b2-07f4-4f06-a123-afe7a0564b95");
        hashMap.put("code", code);
        hashMap.put("grant_type", "authorization_code");
        try {
            AjaxResult ajaxResult = ajaxUtils.doGetWithParams(url, hashMap);
            Object data = ajaxResult.get("data");
            Type type = new TypeReference<Map<String, Object>>() {
            }.getType();
            Map<String, Object> dataResult = JSON.parseObject(data.toString(), type);
            Object err_no = dataResult.get("err_no");
            if (err_no.equals(31005)) {
                return AjaxResult.error("授权失败，从新授权");
            }
            //获取授权信息
            String accessToken = (String) dataResult.get("access_token");
            String expiresIn = (String) dataResult.get("expires_in");
            String scope = (String) dataResult.get("scope");
            String shopId = (String) dataResult.get("shop_id");
            String shopName = (String) dataResult.get("shop_name");
            String refreshToken = (String) dataResult.get("refresh_token");
            String dataStr = JSON.toJSONString(data);
            AccessTokenVO accessTokenVO = JSON.parseObject(dataStr, AccessTokenVO.class);
            //获取用id
            Long userId = loginUser.getUser().getUserId();
            //判断数据库中是否存在该用户
            DoudianUser doudianUserByUserId = doudianUserMapper.getDoudianUserByUserId(userId);
            if (null != doudianUserByUserId) {
                //更新Redis
                redisCache.setCacheObject(shopId, accessTokenVO, Long.parseLong(expiresIn), TimeUnit.MINUTES);
                return AjaxResult.success();
            }
            DoudianUser doudianUser = new DoudianUser();
            doudianUser.setUserId(userId);
            doudianUser.setShopId(shopId);
            doudianUser.setShopName(shopName);
            //存入Redis
            redisCache.setCacheObject(shopId, accessTokenVO, Long.parseLong(expiresIn), TimeUnit.MINUTES);
            //绑定用户与抖店
            doudianUserMapper.bindDoudianByUserId(doudianUser);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /***
     * 获取用户信息
     * @param userId
     * @return
     */
    @Override
    public DoudianUser getDoudianUserByUserId(Long userId) {
        DoudianUser doudianUser = doudianUserMapper.getDoudianUserByUserId(userId);
        return doudianUser;
    }
}
